package com.rosh.rpc.client.spring;

import com.rosh.rpc.client.proxy.CglibProxyFactory;
import com.rosh.rpc.core.annotation.RoshRpcRemote;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Field;

/**
 * @Description:
 * @Author: rosh
 * @Date: 2022/6/14 20:07
 */
@Configuration
public class RpcAnnotationProcessor implements BeanPostProcessor {

    @Autowired
    private CglibProxyFactory cglibProxyFactory;


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        Field[] fields = bean.getClass().getDeclaredFields();

        for (Field filed : fields) {

            if (!filed.isAccessible()) {
                filed.setAccessible(true);
            }
            //生成代理
            RoshRpcRemote rpcRemote = filed.getDeclaredAnnotation(RoshRpcRemote.class);
            if (rpcRemote != null) {
                //创建代理对象
                Object proxyInstance = cglibProxyFactory.newProxyInstance(filed.getType());
                //代理对象注入
                if (proxyInstance != null) {
                    try {
                        filed.set(bean, proxyInstance);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return bean;
    }

}
